package com.shopping.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.shopping.po.Cart;
import com.shopping.po.User;
import com.shopping.service.CartService;

@Controller
public class CartController {
	@Autowired
	private CartService cartService;
	
	@RequestMapping("/insertCart")
	public String insertCart(Integer stock_id,String product,
			Float price,String url,String size,
			HttpSession session,
			HttpServletRequest request,
			RedirectAttributes attr) {
		Cart cart = new Cart();
		cart.setStock_id(stock_id);
		cart.setProduct(product);
		cart.setPrice(price);
		cart.setSize(size);
		cart.setUrl(url);
		User user=(User)session.getAttribute("user");
		Integer user_id =user.getUser_id();
		cart.setUser_id(user_id);;
		cartService.inserCart(cart);
		List<Cart> cart2 =cartService.selectCartbyStock_id(stock_id,user_id);
		
		if(cart != null) {
			request.setAttribute("msg", "成功加入购物车");
			attr.addAttribute("stock_id",stock_id);
			return "forward:/detailGoods";
		}else {
			request.setAttribute("msg", "抱歉，未加入");
			attr.addAttribute("stock_id",stock_id);
			return "forward:/detailGoods";
		}
	}

	@RequestMapping("/lookCart")
	public String lookCart(HttpSession session,Model model) {
		User user=(User)session.getAttribute("user");
		Integer user_id =user.getUser_id();
		List<Cart> cart=cartService.selectCartByUser(user_id);
		model.addAttribute("cart",cart);
		return "cart";
	}
	
	@RequestMapping("/lookCart2")
	public String lookCart2(HttpSession session,Model model) {
		User user=(User)session.getAttribute("user");
		Integer user_id =user.getUser_id();
		List<Cart> cart1=cartService.selectCartByUser(user_id);
		model.addAttribute("cart1",cart1);
		return "cartManager";
	}
	
	@RequestMapping("/deleteCart")
	public String delectCart(HttpServletRequest request, HttpServletResponse response) {
		String[] items = request.getParameterValues("cart_id");
		for (int i = 0; i < items.length; i++) {
				int cart_id = Integer.parseInt(items[i]);
				cartService.deleteCartById(cart_id);
		}
		return "redirect:/lookCart";
	}
	
	
}